<?php

namespace app\common\model;

class DictModel extends BaseModel
{

  protected $table = 'dict';

  /**
   * 按分类获取数据
   * @param $classCode
   * @return \think\Collection
   * @throws \Exception
   */
  public function getDictByClass($classCode)
  {
    return $this->where('class_code', $classCode)->order('show_order asc')->select();
  }

  /**
   * 添加字典
   * @param $data
   * @return DictModel
   * @throws \Exception
   */
  public function add($data)
  {
    $info = $this->where('class_code', $data['class_code'])->where('dict_code', $data['dict_code'])->find();
    if ($info) abort(500, '该编码已存在');
    return self::create($data);
  }

  /**
   * 修改字典
   * @param $data
   * @return DictModel
   * @throws \Exception
   */
  public function edit($data)
  {
    $info = $this->where('id', $data['id'])->find();
    if ($info['dict_code'] != $data['dict_code']) {
      $info = $this->where('class_code', $info['class_code'])->where('dict_code', $data['dict_code'])->find();
      if ($info) abort(500, '该编码已存在');
    }
    return self::update($data);
  }

  /**
   * 删除字典
   * @param $id
   * @return bool
   * @throws \Exception
   */
  public function del($id)
  {
    return $this->where('id', 'in', $id)->delete();
  }
}
